<template>
  <view>
    <text v-if="disabled">{{ firmName }}</text>
    <uni-data-select
      v-else
      v-model="props.firmId"
      :localdata="firmOptions"
      @change="handleChange"
    ></uni-data-select>
  </view>
</template>

<script setup lang="ts">
import {usePmFirmApi} from "@/api/pm/resource/firm";

defineOptions({ name: 'PmFirmSelect' })

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  firmId: {
    type: [String, Number, Array<string | number>],
    default: null,
  },
})

const firmName = computed(() => {
  const list = toRaw(allFirmList.value);
  if (!props.firmId || !list || !list.length) {
    return '暂无';
  } else {
    const customList = Array.isArray(props.firmId) ? props.firmId : [props.firmId]
    const resUser = list.filter((u: PmFirmForm) => customList.includes(u.id));
    if (resUser) {
      const resUserName = resUser.map(custom => {
        return custom.firmName
      })
      return resUserName.join(',');
    }
    return `未知（${props.firmId}）`;
  }
})


type firmOption = {
  value: string | number,
  text: string,
}
const firmOptions = ref<firmOption[]>([]);

function getOptions() {
  const list = toRaw(allFirmList.value);
  if (list && list.length) {
    firmOptions.value = list.map((c: PmFirmForm) => {
      return {
        value: c.id,
        text: c.firmName,
      };
    });
  } else {
    firmOptions.value = [];
  }
}

const $emit = defineEmits(['update:firmId']);
function handleChange(val: string) {
  $emit('update:firmId', val);
}

const allFirmList = ref<PmFirmForm[]>([]);
function getAllFirmList() {
  usePmFirmApi().getAllFirmList().then((res) => {
    if (res.code === 0 && res.data) {
      allFirmList.value = res.data;
      getOptions();
    }
  })
}

onLoad(() => {
  getAllFirmList();
})
</script>

<style scoped lang="scss">

</style>
